package cn.good.yan.w3.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器 - 拦截器
 * @author shengren.yan
 * @create 2023-10-03
 */
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {

    // 拦截前执行  - 目标方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginState = request.getSession().getAttribute("LoginState");
        if(loginState != null){
            return true;
        }
        request.setAttribute("msg","你没有权限，请登录");
        // 转发 登录页
        request.getRequestDispatcher("/login").forward(request,response);
        return false;
    }

    /**
     * 拦截后执行 - 目标方法执行完成以后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}",modelAndView);
    }

    /**
     * 页面渲染以后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}",ex);
    }

}
